<template>
    <el-autocomplete
      ref="autocomplete"
      @keydown.space.native="handleSpace"
      v-model="innerValue"
      :fetch-suggestions="queryUser"
      placeholder="请输入入库人员"
      @select="handleUserSelect"
      :trigger-on-focus="true"
      clearable
      :disabled="disabled"
      style="width: 120px;"
    />
  </template>
  
  <script>
  import { listUser } from '@/api/system/user'
  export default {
    name: "ScmUserInput",
    props: {
      value: String,
      userList: {
        type: Array,
        default: () => []
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        innerValue: this.value || "",
        internalUserList: []
      };
    },
    watch: {
      value(val) {
        this.innerValue = val;
      },
      innerValue(val) {
        this.$emit("input", val);
        this.$emit("update:value", val);
      }
    },
    created() {
      // 如果父组件未传userList，则自动请求
      if (!this.userList || this.userList.length === 0) {
        listUser({}).then(res => {
          this.internalUserList = (res.rows || []).map(user => ({
            value: user.userName,
            pinyin: user.pinyin || '',
            ...user
          }));
        });
      }
    },
    computed: {
      effectiveUserList() {
        // 优先用父组件传入的userList，否则用内部请求的
        return this.userList && this.userList.length > 0 ? this.userList : this.internalUserList;
      }
    },
    methods: {
      queryUser(queryString, cb) {
        const results = this.effectiveUserList.filter(user =>
          user.value.includes(queryString) ||
          (user.pinyin && user.pinyin.includes(queryString.toLowerCase()))
        );
        cb(results);
      },
      handleUserSelect(item) {
        this.innerValue = item.value;
        this.$emit("select", item);
      }, 
      handleSpace(e) {
          this.$refs.autocomplete && this.$refs.autocomplete.focus();
          this.queryUser(this.innerValue, suggestions => {
            this.$refs.autocomplete.suggestions = suggestions;
            this.$refs.autocomplete.visible = true;
          });
        }

    }
  };
  </script>